package cn.signalpha.modules.shop.listener;

import cn.hutool.core.util.NumberUtil;
import cn.signalpha.common.enums.StatusEnum;
import cn.signalpha.common.utils.Arith;
import cn.signalpha.common.utils.Assert;
import cn.signalpha.common.utils.DistanceUtil;
import cn.signalpha.common.utils.SnowflakeUtil;
import cn.signalpha.core.log.exception.ServiceException;
import cn.signalpha.core.tool.jackson.JsonUtil;
import cn.signalpha.core.tool.utils.*;
import cn.signalpha.modules.com.entity.User;
import cn.signalpha.modules.com.service.UserService;
import cn.signalpha.modules.shop.dto.PatternGoodsDTO;
import cn.signalpha.modules.shop.dto.PublicityGoodsDTO;
import cn.signalpha.modules.shop.entity.*;
import cn.signalpha.modules.shop.entity.enums.LogisticsTypeEnum;
import cn.signalpha.modules.shop.entity.enums.OrderStatusEnum;
import cn.signalpha.modules.shop.entity.enums.PatternTypeEnum;
import cn.signalpha.modules.shop.entity.enums.PublicityTypeEnum;
import cn.signalpha.modules.shop.event.OrderSubmitEvent;
import cn.signalpha.modules.shop.order.OrderSubmitOrder;
import cn.signalpha.modules.shop.service.*;
import cn.signalpha.modules.shop.vo.OrderConfirmVO;
import cn.signalpha.modules.shop.vo.OrderDeliveryVO;
import cn.signalpha.modules.shop.vo.OrderGoodsVO;
import cn.signalpha.modules.shop.vo.SellerDeliveryConfigVO;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 提交订单
 */
@AllArgsConstructor
@Component("orderSubmitListener")
public class OrderSubmitListener {

    private final CartService cartService;
	private final UserService userService;
	private final GoodsService goodsService;
	private final SnowflakeUtil snowflakeUtil;
	private final SellerService sellerService;
	private final GoodsSkuService goodsSkuService;
	private final CouponUserService couponUserService;
	private final PlaceLevelService placeLevelService;
	private final OrderCouponService orderCouponService;
	private final PatternGoodsService patternGoodsService;
	private final SellerAddressService sellerAddressService;
	private final SellerCategoryService sellerCategoryService;
	private final PublicityGoodsService publicityGoodsService;

	/**
	 * 默认场景
	 */
    @EventListener(OrderSubmitEvent.class)
	@org.springframework.core.annotation.Order(OrderSubmitOrder.DEFAULT)
    public void defaultOrderSubmitListener(OrderSubmitEvent event) {
		Date dateTime = new Date();
		Long userId = event.getUserId();
		OrderConfirmVO mergerOrder = event.getMergerOrder();
		Assert.isNull(mergerOrder.getUserAddress(), "请填写收货地址");

        // 按商户分单
		Map<Long, Goods> goodsStocksMap = new HashMap<>(16);
		Map<Long, GoodsSku> goodsSkuStocksMap = new HashMap<>(16);
        for (OrderConfirmVO.SellerCartVO sellerCart : mergerOrder.getSellerCartList()) {
			sellerCart.setOrderNo(snowflakeUtil.snowflakeId());

			SellerAddress sellerAddress = null;
			if(sellerCart.getLogisticsType().equals(LogisticsTypeEnum.PICK.getType())){
				Assert.isNull(sellerCart.getSellerAddressId(), "请选择自提地址");
				sellerAddress = sellerAddressService.getById(sellerCart.getSellerAddressId());
				Assert.isNull(sellerAddress, "请选择自提地址");
			}

			OrderDeliveryVO orderDeliveryVO = null;
			if(sellerCart.getLogisticsType().equals(LogisticsTypeEnum.DELIVERY.getType())){
				orderDeliveryVO = new OrderDeliveryVO();
				orderDeliveryVO.setDeliveryDate(sellerCart.getDeliveryDate());
				orderDeliveryVO.setDeliveryBeginTime(sellerCart.getDeliveryBeginTime());
				orderDeliveryVO.setDeliveryEndTime(sellerCart.getDeliveryEndTime());

				//校验距离范围
				if(StringUtil.isAnyBlank(mergerOrder.getUserAddress().getLat(), mergerOrder.getUserAddress().getLng())){
					throw new ServiceException("所选的收货地址经纬度为空，请重新设置收货地址");
				}

				SellerDeliveryConfigVO sellerDeliveryConfig = sellerCart.getSellerDeliveryConfig();
				SellerAddress sellerAddress1 = sellerAddressService.getById(sellerDeliveryConfig.getAddressId());
				if(ObjectUtil.isEmpty(sellerAddress1)){
					throw new ServiceException("商家地址已被删除，请联系商家处理");
				}
				if(StringUtil.isAnyBlank(sellerAddress1.getLat(), sellerAddress1.getLng())){
					throw new ServiceException("商家地址经纬度为空，请联系商家处理");
				}

				double lat1 = Double.parseDouble(mergerOrder.getUserAddress().getLat());
				double lng1 = Double.parseDouble(mergerOrder.getUserAddress().getLng());
				double lat2 = Double.parseDouble(sellerAddress1.getLat());
				double lng2 = Double.parseDouble(sellerAddress1.getLng());
				double distance = DistanceUtil.calculateHaversineDistance(lat1, lng1, lat2, lng2);
				if(distance > sellerDeliveryConfig.getDeliveryScope()){
					throw new ServiceException(StringUtil.format("该地址已超出配送范围，配送范围为{}公里", NumberUtil.decimalFormat(StringPool.HASH, sellerDeliveryConfig.getDeliveryScope())));
				}
			}

			List<OrderDetail> orderDetailList = new ArrayList<>();
            for (OrderConfirmVO.SellerCartItemVO sellerCartItem : sellerCart.getSellerCartItemList()) {
                Goods goods = checkAndGetGoods(sellerCartItem.getGoodsId(), sellerCartItem, goodsStocksMap);
				GoodsSku goodsSku = checkAndGetSku(sellerCartItem.getGoodsSkuId(), sellerCartItem, goodsSkuStocksMap);

				//订单商品详情
				OrderGoodsVO orderGoodsVO = new OrderGoodsVO();
				orderGoodsVO.setId(sellerCartItem.getGoodsId());
				orderGoodsVO.setSn(goods.getSn());
				orderGoodsVO.setName(sellerCartItem.getGoodsName());
				orderGoodsVO.setImg(sellerCartItem.getGoodsImg());
				orderGoodsVO.setType(sellerCartItem.getGoodsType());
				orderGoodsVO.setCategoryId(goods.getCategoryId());
				orderGoodsVO.setGoodsPrice(sellerCartItem.getGoodsPrice());
				orderGoodsVO.setGoodsNum(sellerCartItem.getGoodsNum());
				orderGoodsVO.setGoodsSkuId(sellerCartItem.getGoodsSkuId());
				orderGoodsVO.setGoodsSpec(sellerCartItem.getGoodsSpec());
				orderGoodsVO.setGoodsPriceTotal(sellerCartItem.getGoodsTotalPrice());

				OrderDetail orderDetail = new OrderDetail();
				orderDetail.setSellerId(sellerCart.getSellerId());
				orderDetail.setOrderNo(sellerCart.getOrderNo());
				orderDetail.setUserId(userId);
				orderDetail.setGoodsId(goods.getId());
				orderDetail.setGoodsNum(sellerCartItem.getGoodsNum());
				orderDetail.setGoodsPrice(sellerCartItem.getGoodsPrice());
				orderDetail.setGoodsPriceTotal(sellerCartItem.getGoodsTotalPrice());
				orderDetail.setGoodsDetail(JsonUtil.toJson(orderGoodsVO));
				orderDetail.setDeductMoney(sellerCartItem.getDeductMoney());
				orderDetail.setDeductCouponSeller(sellerCartItem.getDeductCouponSeller());
				orderDetail.setDeductCouponSystem(sellerCartItem.getDeductCouponSystem());
				orderDetail.setDeductIntegral(sellerCartItem.getDeductIntegral());
				orderDetail.setDeductIntegralMoney(sellerCartItem.getDeductIntegralMoney());
				orderDetail.setDeductPublicity(sellerCartItem.getDeductPublicity());
				orderDetail.setDeductPublicityId(sellerCartItem.getDeductPublicityId());
				orderDetail.setDeductPublicityType(sellerCartItem.getDeductPublicityType());
				orderDetail.setDeductPublicityGoodsNum(sellerCartItem.getDeductPublicityGoodsNum());
				if(ObjectUtil.isNotEmpty(sellerCartItem.getDeductPublicityDetail())){
					orderDetail.setDeductPublicityDetail(JsonUtil.toJson(sellerCartItem.getDeductPublicityDetail()));
				}
				orderDetail.setOrderPrice(sellerCartItem.getOrderPrice());
				orderDetail.setDirectMoney(-1d);
				orderDetail.setIndirectMoney(-1d);
				orderDetail.setRefundNum(0);
				orderDetail.setRefundStatus(0);
				orderDetail.setCommentStatus(0);
                orderDetailList.add(orderDetail);
            }

			// 订单信息
            Order order = new Order();
			order.setUserId(userId);
			order.setSellerId(sellerCart.getSellerId());
			order.setOrderNo(sellerCart.getOrderNo());
			order.setGoodsName(Func.join(sellerCart.getSellerCartItemList().stream().map(OrderConfirmVO.SellerCartItemVO::getGoodsName).collect(Collectors.toList())));
			order.setGoodsNum(sellerCart.getGoodsNumTotal());
			order.setGoodsPrice(sellerCart.getGoodsPriceTotal());
			order.setOrderType(sellerCart.getSellerCartItemList().get(0).getGoodsType());
			order.setOrderPrice(sellerCart.getOrderPriceTotal());
			order.setOrderStatus(OrderStatusEnum.UN_PAY.getStatus());
			order.setDeductMoney(sellerCart.getDeductMoney());
			order.setDeductCouponSeller(sellerCart.getDeductCouponSeller());
			order.setDeductCouponSystem(sellerCart.getDeductCouponSystem());
			order.setDeductIntegral(sellerCart.getDeductIntegral());
			order.setDeductPublicity(sellerCart.getDeductPublicity());
			if(ObjectUtil.isNotEmpty(sellerCart.getDeductPublicityDetail())){
				order.setDeductPublicityDetail(JsonUtil.toJson(sellerCart.getDeductPublicityDetail()));
			}
			order.setPayStatus(0);
			order.setLogisticsFee(sellerCart.getTransportFee());
			order.setLogisticsType(sellerCart.getLogisticsType());
			order.setLogisticsInfo(JsonUtil.toJson(mergerOrder.getUserAddress()));
			order.setLogisticsSellerInfo(ObjectUtil.isNotEmpty(sellerAddress) ? JsonUtil.toJson(sellerAddress) : StringPool.EMPTY_JSON);
			order.setLogisticsDeliveryInfo(ObjectUtil.isNotEmpty(orderDeliveryVO) ? JsonUtil.toJson(orderDeliveryVO) : StringPool.EMPTY_JSON);
			order.setBuyerRemark(sellerCart.getRemarks());
			order.setCreateTime(dateTime);
			order.setUpdateTime(dateTime);
			order.setOrderDetailList(orderDetailList);
            event.getOrderList().add(order);

			//插入订单结算表，计算手续费
			double serveRatio;
			Seller seller = sellerService.getById(order.getSellerId());
			Assert.isNull(seller, "未查询到商户信息");
			if(seller.getServerRatioSw() == 1){
				serveRatio = seller.getServerRatio();
			}else{
				SellerCategory sellerCategory = sellerCategoryService.getById(seller.getCategoryId());
				Assert.isNull(sellerCategory, "未查询到商户分类信息");
				serveRatio = sellerCategory.getServerRatio();
			}
			double serveAmount = Arith.round(Arith.mul(order.getOrderPrice(), Arith.div(serveRatio, 100, 4))).doubleValue();
			double settleAmount = Arith.sub(order.getOrderPrice(), serveAmount);
			OrderSettle orderSettle = new OrderSettle();
			orderSettle.setUserId(userId);
			orderSettle.setSellerId(sellerCart.getSellerId());
			orderSettle.setOrderNo(sellerCart.getOrderNo());
			orderSettle.setPayStatus(0);
			orderSettle.setSettleStatus(0);
			orderSettle.setPayAmount(order.getOrderPrice());
			orderSettle.setServeRatio(serveRatio);
			orderSettle.setServeAmount(serveAmount);
			orderSettle.setRefundAmount(0d);
			orderSettle.setSettleWay(1);
			orderSettle.setSettleAmount(settleAmount);
			orderSettle.setCreateTime(dateTime);
			event.getOrderSettleList().add(orderSettle);
        }

        //更新sku库存
        goodsSkuStocksMap.forEach((key, sku) -> {
            if (goodsSkuService.subtractStocks(sku.getId(), sku.getStock()) == 0) {
                throw new ServiceException("商品库存不足");
            }else{
				goodsSkuService.removeCacheByGoodsId(sku.getGoodsId());
			}
        });

        // 更新商品库存
        goodsStocksMap.forEach((goodsId, goods) -> {
            if (goodsService.subtractStocks(goods.getId(), goods.getStock()) == 0) {
                throw new ServiceException("商品库存不足");
            }
        });
    }

	/**
	 * 营销活动场景
	 */
	@EventListener(OrderSubmitEvent.class)
	@org.springframework.core.annotation.Order(OrderSubmitOrder.PUBLICITY)
	public void publicityOrderSubmitListener(OrderSubmitEvent event) {
		List<Order> orderList = event.getOrderList();
		for(Order order : orderList){
			for(OrderDetail orderDetail : order.getOrderDetailList()){

				//限时秒杀
				if(Objects.equals(orderDetail.getDeductPublicityType(), PublicityTypeEnum.LIMIT_TIME_SEC_KILL.getType())){
					PublicityGoods publicityGoods = publicityGoodsService.getOne(Wrappers.<PublicityGoods>lambdaQuery()
						.eq(PublicityGoods::getGoodsId, orderDetail.getGoodsId())
						.eq(PublicityGoods::getPublicityId, orderDetail.getDeductPublicityId())
						.last("limit 1")
					);
					if(ObjectUtil.isNotEmpty(publicityGoods)){
						OrderGoodsVO orderGoodsVO = JsonUtil.parse(orderDetail.getGoodsDetail(), OrderGoodsVO.class);
						PublicityGoodsDTO.LimitTimeSecKillDTO LimitTimeSecKillDTO = JsonUtil.parse(publicityGoods.getConfig(), PublicityGoodsDTO.LimitTimeSecKillDTO.class);
						if(ObjectUtil.isEmpty(LimitTimeSecKillDTO)){
							continue;
						}
						List<PublicityGoodsDTO.LimitTimeSecKillDetailDTO> detailList = LimitTimeSecKillDTO.getDetailList();
						Optional<PublicityGoodsDTO.LimitTimeSecKillDetailDTO> configOptional = detailList.stream().filter(item -> orderGoodsVO.getGoodsSpec().equals(item.getSpec())).findFirst();
						if(!configOptional.isPresent()){
							continue;
						}
						PublicityGoodsDTO.LimitTimeSecKillDetailDTO config = configOptional.get();
						config.setSalesVolume(config.getSalesVolume() + orderDetail.getDeductPublicityGoodsNum());

						PublicityGoods publicityGoodsUpdate = new PublicityGoods();
						publicityGoodsUpdate.setId(publicityGoods.getId());
						publicityGoodsUpdate.setSalesVolume(publicityGoods.getSalesVolume() + orderDetail.getDeductPublicityGoodsNum());
						publicityGoodsUpdate.setConfig(JsonUtil.toJson(LimitTimeSecKillDTO));
						publicityGoodsService.updateById(publicityGoodsUpdate);
					}
				}

				//限时折扣
				if(Objects.equals(orderDetail.getDeductPublicityType(), PublicityTypeEnum.LIMIT_TIME_DISCOUNT.getType())){
					PublicityGoods publicityGoods = publicityGoodsService.getOne(Wrappers.<PublicityGoods>lambdaQuery()
						.eq(PublicityGoods::getGoodsId, orderDetail.getGoodsId())
						.eq(PublicityGoods::getPublicityId, orderDetail.getDeductPublicityId())
						.last("limit 1")
					);
					if(ObjectUtil.isNotEmpty(publicityGoods)){
						OrderGoodsVO orderGoodsVO = JsonUtil.parse(orderDetail.getGoodsDetail(), OrderGoodsVO.class);
						PublicityGoodsDTO.LimitTimeDiscountDTO LimitTimeSecKillDTO = JsonUtil.parse(publicityGoods.getConfig(), PublicityGoodsDTO.LimitTimeDiscountDTO.class);
						if(ObjectUtil.isEmpty(LimitTimeSecKillDTO)){
							continue;
						}
						List<PublicityGoodsDTO.LimitTimeDiscountDetailDTO> detailList = LimitTimeSecKillDTO.getDetailList();
						Optional<PublicityGoodsDTO.LimitTimeDiscountDetailDTO> configOptional = detailList.stream().filter(item -> orderGoodsVO.getGoodsSpec().equals(item.getSpec())).findFirst();
						if(!configOptional.isPresent()){
							continue;
						}
						PublicityGoodsDTO.LimitTimeDiscountDetailDTO config = configOptional.get();
						config.setSalesVolume(config.getSalesVolume() + orderDetail.getDeductPublicityGoodsNum());

						PublicityGoods publicityGoodsUpdate = new PublicityGoods();
						publicityGoodsUpdate.setId(publicityGoods.getId());
						publicityGoodsUpdate.setSalesVolume(publicityGoods.getSalesVolume() + orderDetail.getDeductPublicityGoodsNum());
						publicityGoodsUpdate.setConfig(JsonUtil.toJson(LimitTimeSecKillDTO));
						publicityGoodsService.updateById(publicityGoodsUpdate);
					}
				}
			}
		}
	}

	/**
	 * 优惠券场景
	 */
	@EventListener(OrderSubmitEvent.class)
	@org.springframework.core.annotation.Order(OrderSubmitOrder.COUPON)
	public void couponOrderSubmitListener(OrderSubmitEvent event) {
		List<Order> orderList = event.getOrderList();
		OrderConfirmVO mergerOrder = event.getMergerOrder();

		//处理平台券
		if(CollectionUtil.isNotEmpty(mergerOrder.getCouponsList())){
			Optional<OrderConfirmVO.CouponVO> optional = mergerOrder.getCouponsList().stream().filter(item -> item.getIsSelect() == 1).findFirst();
			if(optional.isPresent()){
				OrderConfirmVO.CouponVO coupon = optional.get();
				List<String> orderNo = orderList.stream().map(Order::getOrderNo).collect(Collectors.toList());
				OrderCoupon orderCoupon = new OrderCoupon();
				orderCoupon.setOrderNo(Func.join(orderNo));
				orderCoupon.setCouponId(coupon.getCouponId());
				orderCoupon.setCouponUserId(coupon.getId());
				orderCoupon.setCouponUseType(coupon.getUseType());
				orderCoupon.setTargetKey(coupon.getTargetKey());
				orderCoupon.setCouponInfo(JsonUtil.toJson(coupon));
				orderCoupon.setCreateTime(orderList.get(0).getCreateTime());
				orderCouponService.save(orderCoupon);
				couponUserService.updateById(CouponUser.builder().id(coupon.getId()).status(1).useTime(orderList.get(0).getCreateTime()).build());
			}
		}

		//处理商户券
		for(OrderConfirmVO.SellerCartVO sellerCart : mergerOrder.getSellerCartList()) {
			if(CollectionUtil.isNotEmpty(sellerCart.getCouponsList())){
				Optional<OrderConfirmVO.CouponVO> optional = sellerCart.getCouponsList().stream().filter(item -> item.getIsSelect() == 1).findFirst();
				if(optional.isPresent()){
					OrderConfirmVO.CouponVO coupon = optional.get();
					Optional<Order> optionalOrder = orderList.stream().filter(i -> i.getSellerId().equals(coupon.getSellerId())).findFirst();
					if(optionalOrder.isPresent()){
						Order order = optionalOrder.get();
						OrderCoupon orderCoupon = new OrderCoupon();
						orderCoupon.setOrderNo(order.getOrderNo());
						orderCoupon.setCouponId(coupon.getCouponId());
						orderCoupon.setCouponUserId(coupon.getId());
						orderCoupon.setCouponUseType(coupon.getUseType());
						orderCoupon.setTargetKey(coupon.getTargetKey());
						orderCoupon.setCouponInfo(JsonUtil.toJson(coupon));
						orderCoupon.setCreateTime(order.getCreateTime());
						orderCouponService.save(orderCoupon);
						couponUserService.updateById(CouponUser.builder().id(coupon.getId()).status(1).useTime(order.getCreateTime()).build());
					}
				}
			}
		}
	}

	/**
	 * 直推佣金场景
	 */
	@EventListener(OrderSubmitEvent.class)
	@org.springframework.core.annotation.Order(500)
	public void directOrderSubmitListener(OrderSubmitEvent event) {
		List<Order> orderList = event.getOrderList();
		for(Order order : orderList){
			//用户是否有上级
			User user = userService.getById(order.getUserId());
			if(ObjectUtil.isEmpty(user.getParentId()) || user.getParentId() == 0){
				continue;
			}
			//上级没有被冻结
			User userParent = userService.getById(user.getParentId());
			if(Objects.equals(userParent.getPlaceStatus(), StatusEnum.OFF.getType())){
				continue;
			}
			for(OrderDetail orderDetail : order.getOrderDetailList()){
				PatternGoods patternGoods = patternGoodsService.getOne(Wrappers.<PatternGoods>lambdaQuery()
					.eq(PatternGoods::getSellerId, order.getSellerId())
					.eq(PatternGoods::getGoodsId, orderDetail.getGoodsId())
					.eq(PatternGoods::getPatternType, PatternTypeEnum.DISTRIBUTION.getType())
				);
				if(ObjectUtil.isEmpty(patternGoods)){
					continue;
				}
				PatternGoodsDTO.DistributionDTO config = JsonUtil.parse(patternGoods.getConfig(), PatternGoodsDTO.DistributionDTO.class);
				if(ObjectUtil.isEmpty(config) || ObjectUtil.isEmpty(config.getType()) || ObjectUtil.isEmpty(config.getCountType())){
					continue;
				}
				if(orderDetail.getOrderPrice() <= 0){
					orderDetail.setDirectMoney(0d);
					continue;
				}
				if(config.getType() == 1){
					//默认配置
					PlaceLevel placeLevel = placeLevelService.getByLevel(userParent.getPlaceLevel());
					if(ObjectUtil.isNotEmpty(placeLevel)){
						//实际支付金额计算佣金
						double ratio = Arith.div(placeLevel.getDirect(), 100, 4);
						double direct = Arith.round(Arith.mul(orderDetail.getOrderPrice(), ratio), 2, RoundingMode.HALF_DOWN).doubleValue();
						orderDetail.setDirectMoney(direct);
					}
				}else if(config.getType() == 2){
					//匹配出规格
					OrderGoodsVO orderGoodsVO = JsonUtil.parse(orderDetail.getGoodsDetail(), OrderGoodsVO.class);
					Optional<PatternGoodsDTO.DistributionDetailDTO> detailOptional = config.getSkuList().stream().filter(i -> i.getSpec().equals(orderGoodsVO.getGoodsSpec())).findFirst();
					if(detailOptional.isPresent()){
						PatternGoodsDTO.DistributionDetailDTO detailDTO = detailOptional.get();
						//匹配出直推等级
						Optional<PatternGoodsDTO.DistributionDetailLevelDTO> detailLevelOptional = detailDTO.getLevelList().stream().filter(i -> i.getLevel().equals(userParent.getPlaceLevel())).findFirst();
						if(detailLevelOptional.isPresent()){
							PatternGoodsDTO.DistributionDetailLevelDTO detailLevelDTO = detailLevelOptional.get();
							if(config.getCountType() == 1){
								double ratio = Arith.div(detailLevelDTO.getDirect(), 100, 4);
								double direct = Arith.round(Arith.mul(orderDetail.getOrderPrice(), ratio), 2, RoundingMode.HALF_DOWN).doubleValue();
								orderDetail.setDirectMoney(direct);
							}else{
								double direct = Arith.mul(detailLevelDTO.getDirect(), orderDetail.getGoodsNum());
								orderDetail.setDirectMoney(direct);
							}
						}
					}
				}
			}
		}
	}

	/**
	 * 间推佣金场景
	 */
	@EventListener(OrderSubmitEvent.class)
	@org.springframework.core.annotation.Order(501)
	public void indirectOrderSubmitListener(OrderSubmitEvent event) {
		List<Order> orderList = event.getOrderList();
		for(Order order : orderList){
			//用户是否有上上级
			User user = userService.getById(order.getUserId());
			if(ObjectUtil.isEmpty(user.getGrandpaId()) || user.getGrandpaId() == 0){
				continue;
			}
			//上上级没有被冻结
			User userGrandpa = userService.getById(user.getGrandpaId());
			if(Objects.equals(userGrandpa.getPlaceStatus(), StatusEnum.OFF.getType())){
				continue;
			}
			for(OrderDetail orderDetail : order.getOrderDetailList()){
				PatternGoods patternGoods = patternGoodsService.getOne(Wrappers.<PatternGoods>lambdaQuery()
					.eq(PatternGoods::getSellerId, order.getSellerId())
					.eq(PatternGoods::getGoodsId, orderDetail.getGoodsId())
					.eq(PatternGoods::getPatternType, PatternTypeEnum.DISTRIBUTION.getType())
				);
				if(ObjectUtil.isEmpty(patternGoods)){
					continue;
				}
				PatternGoodsDTO.DistributionDTO config = JsonUtil.parse(patternGoods.getConfig(), PatternGoodsDTO.DistributionDTO.class);
				if(ObjectUtil.isEmpty(config) || ObjectUtil.isEmpty(config.getType()) || ObjectUtil.isEmpty(config.getCountType())){
					continue;
				}
				if(orderDetail.getOrderPrice() <= 0){
					orderDetail.setIndirectMoney(0d);
					continue;
				}
				if(config.getType() == 1){
					//默认配置
					PlaceLevel placeLevel = placeLevelService.getByLevel(userGrandpa.getPlaceLevel());
					if(ObjectUtil.isNotEmpty(placeLevel)){
						//实际支付金额计算佣金
						double ratio = Arith.div(placeLevel.getIndirect(), 100, 4);
						double direct = Arith.round(Arith.mul(orderDetail.getOrderPrice(), ratio), 2, RoundingMode.HALF_DOWN).doubleValue();
						orderDetail.setIndirectMoney(direct);
					}
				}else if(config.getType() == 2){
					//匹配出规格
					OrderGoodsVO orderGoodsVO = JsonUtil.parse(orderDetail.getGoodsDetail(), OrderGoodsVO.class);
					Optional<PatternGoodsDTO.DistributionDetailDTO> detailOptional = config.getSkuList().stream().filter(i -> i.getSpec().equals(orderGoodsVO.getGoodsSpec())).findFirst();
					if(detailOptional.isPresent()){
						PatternGoodsDTO.DistributionDetailDTO detailDTO = detailOptional.get();
						//匹配出直推等级
						Optional<PatternGoodsDTO.DistributionDetailLevelDTO> detailLevelOptional = detailDTO.getLevelList().stream().filter(i -> i.getLevel().equals(userGrandpa.getPlaceLevel())).findFirst();
						if(detailLevelOptional.isPresent()){
							PatternGoodsDTO.DistributionDetailLevelDTO detailLevelDTO = detailLevelOptional.get();
							if(config.getCountType() == 1){
								double ratio = Arith.div(detailLevelDTO.getIndirect(), 100, 4);
								double direct = Arith.round(Arith.mul(orderDetail.getOrderPrice(), ratio), 2, RoundingMode.HALF_DOWN).doubleValue();
								orderDetail.setIndirectMoney(direct);
							}else{
								double direct = Arith.mul(detailLevelDTO.getIndirect(), orderDetail.getGoodsNum());
								orderDetail.setIndirectMoney(direct);
							}
						}
					}
				}
			}
		}
	}


    @SuppressWarnings({"Duplicates"})
    private Goods checkAndGetGoods(Long goodsId, OrderConfirmVO.SellerCartItemVO sellerCartItem, Map<Long, Goods> prodStocksMap) {
        Goods goods = goodsService.getById(goodsId);
        if (goods == null) {
            throw new ServiceException("购物车包含无法识别的商品");
        }

        if (goods.getStatus() != 1) {
            throw new ServiceException("商品[" + goods.getName() + "]已下架");
        }

        // 商品需要改变的库存
        Goods mapGoods = prodStocksMap.get(goodsId);

        if (mapGoods == null) {
            mapGoods = new Goods();
            mapGoods.setId(goodsId);
            mapGoods.setStock(0);
        }

        if (goods.getStock() != -1) {
            mapGoods.setStock(mapGoods.getStock() + sellerCartItem.getGoodsNum());
            prodStocksMap.put(goods.getId(), mapGoods);
        }

        if (mapGoods.getStock() > goods.getStock()) {
            throw new ServiceException("商品：[" + goods.getName() + "]库存不足");
        }

        return goods;
    }

    @SuppressWarnings({"Duplicates"})
    private GoodsSku checkAndGetSku(Long skuId, OrderConfirmVO.SellerCartItemVO sellerCartItem, Map<Long, GoodsSku> skuStocksMap) {
        // 获取sku信息
        GoodsSku sku = goodsSkuService.getById(skuId);
        if (sku == null) {
            throw new ServiceException("购物车包含无法识别的商品");
        }

        if (sellerCartItem.getGoodsNum() > sku.getStock()) {
            throw new ServiceException("商品：[" + sellerCartItem.getGoodsNum() + "]库存不足");
        }

        if (sku.getStock() != -1) {
            GoodsSku mapSku = new GoodsSku();
            // 这里的库存是改变的库存
            mapSku.setStock(sellerCartItem.getGoodsNum());
            mapSku.setId(sku.getId());
			mapSku.setGoodsId(sku.getGoodsId());
            skuStocksMap.put(sku.getId(), mapSku);
        }
        return sku;
    }

}
